import { Injectable } from '@angular/core';
import {
  Http,
  Response,
  URLSearchParams,
  Headers,
  RequestOptions,
  RequestOptionsArgs
} from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { environment } from '../../../environments/environment';
// import { HttpParams } from '@angular/common/http';
import { HttpClient, HttpParams } from '@angular/common/http';


@Injectable()
export class LoginService {
    private apiBaseUrl = environment.apiBaseUrl;

    user: any;

    constructor (private http: HttpClient) {}

    setUser(data) {
        this.user = data;
        localStorage.setItem('eyoule-recipes', JSON.stringify(this.user));
    }

    getUser() {
        if (!this.user) {
            if (JSON.parse(localStorage.getItem('eyoule-recipes'))) {
                this.user = JSON.parse(localStorage.getItem('eyoule-recipes'));
            } else {
                this.user = '';
            }
        }
        return this.user;
    }

    login(param: object): Observable<object> {
        // const headers = new Headers();
        // headers.append('Content-Type', 'application/x-www-form-urlencoded');
        const params = new HttpParams()
            .set('username', param['username'])
            .set('password', param['password'])
            .set('captcha', param['captcha']);
        return this.http.post(this.apiBaseUrl + 'admin/login', params)
                // .map(res => res.text() ? res.json() : {})
                .catch(this.handleError);
    }

    signOut () {
        localStorage.removeItem('eyoule-recipes');
        this.user = '';
    }

    private extractData(res: Response) {
        const body = res.json();
        return body || { };
    }

    private handleError (error: Response | any) {
        return Observable.throw(error);
    }

}
